<?php

class myCultureFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // execute this filter only once
    if ($this->isFirstCall())
    {      
      //set internal character encoding for mb_* functions
      mb_internal_encoding('UTF-8');
      mb_regex_encoding('UTF-8');
      
      $con = Propel::getConnection();
      
      if ($con){
         $con->exec("SET NAMES 'utf8'");
         $con->exec("SET CHARACTER SET utf8");
      } else {
        throw new Exception($e);
      } 

      $sf_user = $this->getContext()->getUser();      
      $sf_request = $this->getContext()->getRequest();
      $sf_response = $this->getContext()->getResponse();
            
      if($sf_request->getParameter('lang'))
      {
        $language = LanguagePeer::retrieveByLang($sf_request->getParameter('lang'));
        $culture = ($language instanceof Language) ? $language->getCulture() : sfConfig::get('sf_default_culture');
        $sf_user->setCulture($culture);
        $sf_user->setDirection(($language instanceof Language) ? $language->getDir() : sfConfig::get('sf_factories_i18n_default_direction'));
      }
      elseif ($sf_request->getCookie('culture'))
      {
        $language = LanguagePeer::retrieveByCulture($sf_request->getCookie('culture'));
        $culture = ($language instanceof Language) ? $language->getCulture() : sfConfig::get('sf_default_culture'); 
        $sf_user->setCulture($culture);
        $sf_user->setDirection(($language instanceof Language) ? $language->getDir() : sfConfig::get('sf_factories_i18n_default_direction'));
      }
      else
      { 
        $sf_user->setCulture(sfConfig::get('sf_default_culture'));
        $sf_user->setDirection(sfConfig::get('sf_factories_i18n_default_direction'));
      }
    
      // set culture cookie
      if( $sf_request->getCookie('culture') != $sf_user->getCulture())
      {                                          
        $sf_response->setCookie('culture', $sf_user->getCulture(), time()+60*60*24*15, '/');
      }
    
      // set page title
      $sf_response->setTitle($this->getContext()->getI18n()->__(sfConfig::get('app_site_title')));
    
      // set culture direction dependant stylesheet
      $sf_response->addStylesheet($this->getContext()->getUser()->getDirection(), 'last');
    }
    
    // execute next filter
    $filterChain->execute();
  }
}
